<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\RouteModel;
use cmf\controller\AdminBaseController;

use think\Db;

/**
 * Class SettingController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   =>'设置',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 0,
 *     'icon'   =>'cogs',
 *     'remark' =>'系统设置入口'
 * )
 */
class SettingController extends AdminBaseController
{

    /**
     * 网站信息
     * @adminMenu(
     *     'name'   => '网站信息',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '网站信息',
     *     'param'  => ''
     * )
     */
    public function site()
    {

        $noNeedDirs     = [".", "..", ".svn", 'fonts'];
        $adminThemesDir = config('cmf_admin_theme_path') . config('cmf_admin_default_theme') . '/public/assets/themes/';
        $adminStyles    = cmf_scan_dir($adminThemesDir . '*', GLOB_ONLYDIR);
        $adminStyles    = array_diff($adminStyles, $noNeedDirs);
        $cdnSettings    = cmf_get_option('cdn_settings');
        $cmfSettings    = cmf_get_option('cmf_settings');
        $adminSettings  = cmf_get_option('admin_settings');
   

        $this->assign(cmf_get_option('site_info'));
        $this->assign("admin_styles", $adminStyles);
        $this->assign("templates", []);
        $this->assign("cdn_settings", $cdnSettings);
        $this->assign("admin_settings", $adminSettings);
        $this->assign("cmf_settings", $cmfSettings);

        return $this->fetch();
    }


    /**
     * 错误日志
     * @adminMenu(
     *     'name'   => '错误日志',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 0,
     *     'icon'   => '',
     *     'remark' => '错误日志',
     *     'param'  => ''
     * )
     */
    public function log_list()
    {
        //初始清除缓存
        cache('content_array',null);

        cache('start_time',null);

        //获取当前月份和日期
        $param = $this->request->param();
      

        // $start_time = empty($param['start_time']) ? time() : strtotime($param['start_time']);
        if(empty($param['start_time']) && empty($_GET['start_time']) && empty($stime)){
     
            $start_time = time();

        }else{
            
            $start_time = empty($param['start_time']) ? $_GET['start_time'] : strtotime($param['start_time']);

            if($stime){
                
                $start_time = cache('start_time');

            }else if($param['start_time'] && empty($stime)){
               
                $start_time = strtotime($param['start_time']);
            }else{
                
                $start_time = $_GET['start_time'];
            }
           
        }
        
        
        $page = empty($param['page']) ? '1' : $param['page'];

        $size = 10;

        $pagedata = array();

        //开始排序号
        $start_x = ($page-1)*$size+1;

        if(empty($param['err_level'])){
            $err_level = 'error';
        }else if($param['err_level'] == 1){
            $err_level = 'debug';
        }else{
            $err_level = 'notice';
        }

        // $keyword = htmlspecialchars($param['keyword']);
        $keyword = $this->request->param('keyword','','trim');


        

        //获取当前条件下的错误日志
        $count = 0;
        if(cache('content_array') && (date('Y-m-d',cache('start_time')) === date('Y-m-d',$start_time))){
           
            $list = cache('content_array');

            $count = count($list);
            //总页数
            $sum_page = ceil($count/$size);

            //每次分页开始位置
            $start=($page-1)*$size;

            $pagedata = array_slice($list,$start,$size);

            foreach($pagedata as $key=>$val){

                $data_list[$start_x+$key]=$val;
            }


        }else{
           

            $dir = CMF_ROOT.'data/runtime/log/'.date('Ym',$start_time).'/'.date('d',$start_time).'_'.$err_level.'.log';
         
            if(file_exists($dir)){

                

                $content_array = file($dir);
                $content_array = array_unique($content_array);

                if(is_array($content_array)){


                    foreach($content_array as $key=>$val){

                        if(preg_match('/'.$err_level.'/', $val)){

                            if(!empty($keyword) && !preg_match('/'.$keyword.'/', $val)){

                                unset($content_array[$key]);
                            }

                        }else{

                            unset($content_array[$key]);

                        }

                        // if(!preg_match('/'.$err_level.'/', $val)){

                        //     unset($content_array[$key]);
                        // }


                        // if(preg_match('/-------/',$val)){
                        //     unset($content_array[$key]);
                        // }
                        
                        // if(!empty($keyword) && !preg_match('/'.$keyword.'/', $val)){

                        //     unset($content_array[$key]);
                        // }

                    }

                }

                $count = count($content_array);
                //总页数
                $sum_page = ceil($count/$size);

                //每次分页开始位置
                $start=($page-1)*$size;

                $pagedata = array_slice($content_array,$start,$size);

                cache('content_array', $content_array, 86400);

                $stime = cache('start_time', $start_time, 86400);

                foreach($pagedata as $key=>$val){

                    $data_list[$start_x+$key]=$val;
                }

            }else{

                // $pagedata = array();
                $data_list = array();
            }



        }

            
 // pre($data_list,1);
        $this->assign('data_list',  $data_list);

        $url = 'log_list';


        $this->assign('downfile',   cmf_get_file_download_url('../../data/runtime/log/'.date('Ym',$start_time).'/'.date('d',$start_time).'_'.$err_level.'.log'));
        $this->assign('start_time', date('Y-m-d',$start_time));

        $this->assign('err_level', $err_level);
        $this->assign('keyword', $keyword);

        if($data_list){
            $this->assign('page',   $this->show_array($sum_page,$url,$start_time,$page,$keyword,$count));
        }
        
        $this->assign('now_page',   $page);
        $this->assign('size',   $size);
        $this->assign('count',   $count);
        
        return $this->fetch();
    }

    /**
     * 数组分页
     * @param  $countpage 总页数
     * @param  $url       当前url
     */
    public function show_array($countpage,$url,$start_time,$page,$keyword,$count=0){     
  

    
        // $page=empty($_GET['page'])?1:$_GET['page']; 
        
        $page = empty($page) ? 1 : $page;

        if($page > 1){      
            $uppage=$page-1;      
        }else{      
            $uppage=1;      
        }      
          
        if($page < $countpage){     

            $nextpage=$page+1;      
          
        }else{      
            $nextpage=$countpage;      
        }      
                 
        
        $start_time = date('Y-m-d',$start_time);


        $str='<div style="border:1px; width:400px; height:30px; color:#9999CC">';      
        $str.="<span>第 {$page} 页  / 共  {$countpage}  页，{$count} 条记录</span>";
        if( $countpage>1 ){
            $str.="<span><a href='$url?page=1&start_time={$start_time}&keyword={$keyword}'>   首页  </a></span>";      
            $str.="<span><a href='$url?page={$uppage}&start_time={$start_time}&keyword={$keyword}'> 上一页  </a></span>";      
            $str.="<span><a href='$url?page={$nextpage}&start_time={$start_time}&keyword={$keyword}'>下一页  </a></span>";      
            $str.="<span><a href='$url?page={$countpage}&start_time={$start_time}&keyword={$keyword}'>尾页  </a></span>";      
        }
        $str.='</div>'; 


        return $str;      
    }

    //验证文件是否存在
    public function is_ext(){

        $param = $this->request->param();

        $time = strtotime($param['d_time']);

        $err_level = $param['err_level'];

        $keyword = $param['keyword'];

        //判断文件是否存在
        
        $dir = RUNTIME_PATH.'log/'.date('Ym',$time).'/'.date('d',$time).'_'.$param['err_level'].'.log';

        if(file_exists($dir)){


            $content_array = file($dir);
            $content_array = array_unique($content_array);

            if(is_array($content_array)){


                foreach($content_array as $key=>$val){

                    
                    if(preg_match('/'.$err_level.'/', $val)){

                        if(!empty($keyword) && !preg_match('/'.$keyword.'/', $val)){

                            unset($content_array[$key]);
                        }

                    }else{

                        unset($content_array[$key]);

                    }

                    
                }
                
                $new_file = RUNTIME_PATH.'log/'.date('Ym',$time).'/'.date('d',$time).'_'.$param['err_level'].'_down.txt';
                
                if(fopen($new_file,'w')){

                    foreach($content_array as $kk=>$value){

                        file_put_contents($new_file,$value,FILE_APPEND);
                    }

                    if(file_exists($new_file)){


                        $result['status'] = 1;
                        $result['msg']    = '导出文件生成成功';
                        $result['file_url'] = date('d',$time).'_'.$param['err_level'].'_down.txt';
                        $result['times'] = date('Ym',$time);

                    }else{

                        $result['status'] = 1;
                        $result['msg']    = '导出文件生成失败';
                    }
                    

                    // $result['status'] = 1;
                    // $result['msg']    = '导出文件生成成功';
                    // // $result['file_url']  = cmf_get_domain().'/data/runtime/log/'.date('Ym',$time).'/'.date('d',$time).'_'.$param['err_level'].'_down.txt';
                    // $result['file_url']  = cmf_download($new_file);

                    
                    
                }else{


                    $result ['status'] = 0;
                    $result ['msg'] = '导出失败！';
                    


                }

  
            }


            

        }else{

            $result ['status'] = 0;
            $result ['msg'] = '文件不存在！';

        }

        echo json_encode($result);

    }

    //下载日志
    public function download(){

        $param = $this->request->param();

        $filename=RUNTIME_PATH.'log/'.$param['time'].'/'.$param['down_file'];
       
    
        
        Header( "Content-type:  application/octet-stream "); 
        Header( "Accept-Ranges:  bytes "); 
        Header( "Accept-Length: " .filesize($filename));
        header( "Content-Disposition:  attachment;  filename= ".$param['down_file']); 

        echo file_get_contents($filename);
        exit();
        // readfile($filename);

       
    }

    //删除日志文件
    public function del_is_ext(){

        $param = $this->request->param();

        $time = strtotime($param['d_time']);

        $err_level = $param['err_level'];

        $keys = $param['del_id'];
        //判断文件是否存在
    
        $dir = RUNTIME_PATH.'log/'.date('Ym',$time).'/'.date('d',$time).'_'.$param['err_level'].'.log';

        if(file_exists($dir)){


            $content_array = file($dir);
            $content_array = array_unique($content_array);

            if(is_array($content_array)){


                foreach($content_array as $key=>$val){

                    
                    if(preg_match('/'.$err_level.'/', $val)){

                        
                    }else{

                        unset($content_array[$key]);
                    }

                    
                    
                }



                $content_array = array_values($content_array);

                $content = $content_array[$keys-1];


                $content_file = file_get_contents($dir);

                $newcontent = str_replace($content, "", $content_file);


                file_put_contents($dir,$newcontent);
          

                
            }


            // @unlink($dir);

            $result ['status'] = 1;
            $result ['msg'] = '删除成功';

            

        }else{

            $result ['status'] = 0;
            $result ['msg'] = '文件不存在！';

        }

        echo json_encode($result);

    }





    /**
     * 网站信息设置提交
     * @adminMenu(
     *     'name'   => '网站信息设置提交',
     *     'parent' => 'site',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '网站信息设置提交',
     *     'param'  => ''
     * )
     */
    public function sitePost()
    {
        if ($this->request->isPost()) {

            $result = $this->validate($this->request->param(), 'SettingSite');
           
            if ($result !== true) {
                $this->error($result);
            }

            $options = $this->request->param('options/a');
            cmf_set_option('site_info', $options);

            $cmfSettings = $this->request->param('cmf_settings/a');

            $bannedUsernames                 = preg_replace("/[^0-9A-Za-z_\\x{4e00}-\\x{9fa5}-]/u", ",", $cmfSettings['banned_usernames']);
            $cmfSettings['banned_usernames'] = $bannedUsernames;
            cmf_set_option('cmf_settings', $cmfSettings);

            $cdnSettings = $this->request->param('cdn_settings/a');
            cmf_set_option('cdn_settings', $cdnSettings);

            $adminSettings = $this->request->param('admin_settings/a');

            $routeModel = new RouteModel();
            if (!empty($adminSettings['admin_password'])) {
                $routeModel->setRoute($adminSettings['admin_password'].'$', 'admin/Index/index', [], 2, 5000);
            } else {
                $routeModel->deleteRoute('admin/Index/index', []);
            }

            $routeModel->getRoutes(true);

            cmf_set_option('admin_settings', $adminSettings);
                

            //操作日志
            admin_log('','edit','编辑网站设置');

            $this->success("保存成功！", '');

        }
    }

    /**
     * 密码修改
     * @adminMenu(
     *     'name'   => '密码修改',
     *     'parent' => 'default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '密码修改',
     *     'param'  => ''
     * )
     */
    public function password()
    {
        return $this->fetch();
    }

    /**
     * 密码修改提交
     * @adminMenu(
     *     'name'   => '密码修改提交',
     *     'parent' => 'password',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '密码修改提交',
     *     'param'  => ''
     * )
     */
    public function passwordPost()
    {
        if ($this->request->isPost()) {

            $data = $this->request->param();
            if (empty($data['old_password'])) {
                $this->error("原始密码不能为空！");
            }
            if (empty($data['password'])) {
                $this->error("新密码不能为空！");
            }

            $userId = cmf_get_current_admin_id();

            $admin = Db::name('user')->where(["id" => $userId])->find();

            $oldPassword = $data['old_password'];
            $password    = $data['password'];
            $rePassword  = $data['re_password'];

            if (cmf_compare_password($oldPassword, $admin['user_pass'])) {
                if ($password == $rePassword) {

                    if (cmf_compare_password($password, $admin['user_pass'])) {
                        $this->error("新密码不能和原始密码相同！");
                    } else {
                        Db::name('user')->where('id', $userId)->update(['user_pass' => cmf_password($password)]);

                        //操作日志
                        admin_log('', 'edit', 'PASSWORD');

                        $this->success("密码修改成功！");
                    }
                } else {
                    $this->error("密码输入不一致！");
                }

            } else {
                $this->error("原始密码不正确！");
            }
        }
    }

    /**
     * 上传限制设置界面
     * @adminMenu(
     *     'name'   => '上传设置',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '上传设置',
     *     'param'  => ''
     * )
     */
    public function upload()
    {
        $uploadSetting = cmf_get_upload_setting();
        $this->assign($uploadSetting);

        $waterSettings = cmf_get_option('water_settings');
        $this->assign("water_settings", $waterSettings);
        
        return $this->fetch();
    }

    /**
     * 上传限制设置界面提交
     * @adminMenu(
     *     'name'   => '上传设置提交',
     *     'parent' => 'upload',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '上传设置提交',
     *     'param'  => ''
     * )
     */
    public function uploadPost()
    {
        if ($this->request->isPost()) {
            //TODO 非空验证
            // $uploadSetting = $this->request->post();
            $uploadSetting = $this->request->param('upload_setting/a');
            //上传的文件是否重命名
            $uploadSetting['is_rename'] = empty($uploadSetting['is_rename'])? 0 :1;
            cmf_set_option('upload_setting', $uploadSetting);


            $waterSettings = $this->request->param('water_settings/a');
            if( !empty($waterSettings['water_img']) ){
                $waterSettings['water_img'] = cmf_asset_relative_url($waterSettings['water_img']);
            }
            cmf_set_option('water_settings', $waterSettings);

            //操作日志
            admin_log('','edit','upload_setting');

            $this->success('保存成功！');
        }

    }

    /**
     * 微信相关设置界面
     * @adminMenu(
     *     'name'   => '微信相关设置',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '上传设置',
     *     'param'  => ''
     * )
     */
    public function wechat()
    {
        $wechatSetting = cmf_get_option('wechat_setting');


        $this->assign("audit_list", get_audit_flow($wechatSetting['audit_id']));  //审核流程列表

        $this->assign($wechatSetting);
        return $this->fetch();
    }

    /**
     * 微信相关设置界面提交
     * @adminMenu(
     *     'name'   => '上传设置提交',
     *     'parent' => 'upload',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '上传设置提交',
     *     'param'  => ''
     * )
     */
    public function wechatPost()
    {
        if ($this->request->isPost()) {
            //TODO 非空验证
            $wechatSetting = $this->request->post();

            cmf_set_option('wechat_setting', $wechatSetting);

            //操作日志
            admin_log('', 'edit', '微信相关设置');

            $this->success('保存成功！');
        }

    }
    
    /**
     * 清除缓存
     * @adminMenu(
     *     'name'   => '清除缓存',
     *     'parent' => 'default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '清除缓存',
     *     'param'  => ''
     * )
     */
    public function clearCache()
    {
        cmf_clear_cache(['log']);
        return $this->fetch();
    }


}
